package com.gh.yygh.user.api;

import com.alibaba.excel.util.StringUtils;
import com.alibaba.fastjson.JSONObject;
import com.gh.yygh.common.exception.YyghException;
import com.gh.yygh.common.helper.JwtHelper;
import com.gh.yygh.common.result.Result;
import com.gh.yygh.common.result.ResultCodeEnum;
import com.gh.yygh.model.user.UserInfo;
import com.gh.yygh.user.service.UserInfoService;
import com.gh.yygh.user.utils.ConstantWxPropertiesUtil;
import com.gh.yygh.user.utils.HttpClientUtils;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

@Api(tags = "微信登录接口")
@Controller
@RequestMapping("/api/ucenter/wx")
public class WeixinApiController {
    @Autowired
    private UserInfoService userInfoService;
    @Autowired
    private RedisTemplate redisTemplate;


    /*
    * 获取回调参数
    * */
    @RequestMapping("callback")
    public String callback(String code, String state) {
        //获取授权临时票据
        System.out.println("微信授权服务器回调。。。。。。");
        System.out.println("state = " + state);
        System.out.println("code = " + code);

        if (StringUtils.isEmpty(state) || StringUtils.isEmpty(code)) {
            throw new YyghException(ResultCodeEnum.ILLEGAL_CALLBACK_REQUEST_ERROR);
        }

        //使用code和appid以及appscrect换取access_token
        StringBuffer baseAccessTokenUrl = new StringBuffer()
                .append("https://api.weixin.qq.com/sns/oauth2/access_token")
                .append("?appid=%s")
                .append("&secret=%s")
                .append("&code=%s")
                .append("&grant_type=authorization_code");
        System.out.println("baseAccessTokenUrl = " + baseAccessTokenUrl);

        System.out.println("baseAccessTokenUrl.toString = " + baseAccessTokenUrl.toString());
        String accessTokenUrl = String.format(baseAccessTokenUrl.toString(),
                ConstantWxPropertiesUtil.WX_OPEN_APP_ID,
                ConstantWxPropertiesUtil.WX_OPEN_APP_SECRET,
                code);

        try {
            String result = HttpClientUtils.get(accessTokenUrl);
            System.out.println("result = " + result);

            //根据返回字符串获得openId和accessToken
            JSONObject resultJson = JSONObject.parseObject(result);
            System.out.println("resultJson = " + resultJson);
            String access_token = resultJson.getString("access_token");
            String openId = resultJson.getString("openid");
            System.out.println("accessToken = " + access_token);
            System.out.println("openId = " + openId);

            //判断openId是否存在
            UserInfo userInfo = userInfoService.selectWxInfoOpenId(openId);
            if(userInfo == null){//数据库不存在微信信息
                //拿着openid和access_token请求微信地址，得到扫描人信息
                String baseUserInfoUrl = "https://api.weixin.qq.com/sns/userinfo" +
                        "?access_token=%s" +
                        "&openid=%s";
                String userInfoUrl = String.format(baseUserInfoUrl, access_token, openId);
                String resultUserInfo = HttpClientUtils.get(userInfoUrl);
                System.out.println("resultUserInfo = " + resultUserInfo);

                //获取返回结果的具体值
                JSONObject resultUserInfoJson = JSONObject.parseObject(resultUserInfo);

                //解析用户信息
                String nickname = resultUserInfoJson.getString("nickname");
                String headimgurl = resultUserInfoJson.getString("headimgurl");

                userInfo = new UserInfo();
                userInfo.setOpenid(openId);
                userInfo.setNickName(nickname);
                userInfo.setStatus(1);
                userInfoService.save(userInfo);
            }

            //返回name和token字符串
            Map<String, String > map = new HashMap<>();
            String name = userInfo.getName();
            if(StringUtils.isEmpty(name)) {
                name = userInfo.getNickName();
            }
            if(StringUtils.isEmpty(name)) {
                name = userInfo.getPhone();
            }
            map.put("name", name);
            if(StringUtils.isEmpty(userInfo.getPhone())) {
                map.put("openid", userInfo.getOpenid());
            } else {
                map.put("openid", "");
            }
            String token = JwtHelper.createToken(userInfo.getId(), name);
            map.put("token", token);
            return "redirect:" + ConstantWxPropertiesUtil.YYGH_BASE_URL
                    + "/weixin/callback?token="+map.get("token")+"&openid="
                    +map.get("openid")+"&name="
                    +URLEncoder.encode(map.get("name"),"utf-8");
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

        /**
         * 获取微信登录参数
         */
    @GetMapping("getLoginParam")
    @ResponseBody
    public Result genQrConnect(){
        try {
            String wxOpenRedirectUrl = ConstantWxPropertiesUtil.WX_OPEN_REDIRECT_URL;
            String redirectUri = URLEncoder.encode(wxOpenRedirectUrl, "utf-8");
            Map<String, Object> map = new HashMap<>();
            map.put("appid", ConstantWxPropertiesUtil.WX_OPEN_APP_ID);
            map.put("redirect_uri", redirectUri);
            map.put("scope", "snsapi_login");
            map.put("state", System.currentTimeMillis() + "");//System.currentTimeMillis()+""
            return Result.ok(map);
        }catch (UnsupportedEncodingException e){
            e.printStackTrace();
            return null;
        }
    }

}
